package week07

import "math"

// 8. 字符串转换整数 (atoi)
// https://leetcode-cn.com/problems/string-to-integer-atoi/

func myAtoi(s string) int {
	var index = 0
	var bytes = []byte(s)
	for ; index < len(bytes) && bytes[index] == ' '; index++ {}
	var sign = 1
	if index < len(bytes) && (bytes[index] == '-' || bytes[index] == '+') {
		if bytes[index] == '-' {
			sign = -1
		}
		index++
	}
	var val = 0
	for ; index < len(bytes) && bytes[index] >= '0' && bytes[index] <= '9'; index++ {
		if val > (math.MaxInt32 - int(bytes[index]-'0')) / 10 {
			if sign < 0 {
				return math.MinInt32
			}
			return math.MaxInt32
		}
		val = val * 10 + int(bytes[index]-'0')
	}
	return val * sign
}